package ar.com.sectorwine.repository;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ImportResource( "classpath*:*spring-data-config.xml" )
public class PersistenceJPAConfig {


	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
		LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
		factoryBean.setDataSource(restDataSource());
		// factoryBean.setPackagesToScan( new String[ ] { "org.rest" } );
		factoryBean.setPackagesToScan(new String[] { "ar.com.sectorwine.entities" });

		JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter() {
			{
				// JPA properties
				setShowSql(true);
				setDatabase(Database.POSTGRESQL);
				setGenerateDdl(false);
			}
		};
		factoryBean.setJpaVendorAdapter(vendorAdapter);
		factoryBean.setJpaProperties(additionlProperties());

		return factoryBean;
	}

	@Bean(name="dataSource")
	public DataSource restDataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("org.postgresql.Driver");
		dataSource.setUrl("jdbc:postgresql://localhost:5432/sectorwine");
		dataSource.setUsername("sectorwine");
		dataSource.setPassword("sectorwine");
		return dataSource;
	}

	@Bean
	public PlatformTransactionManager transactionManager() {
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		transactionManager.setEntityManagerFactory(entityManagerFactoryBean()
				.getObject());

		return transactionManager;
	}

	@Bean
	public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
		return new PersistenceExceptionTranslationPostProcessor();
	}

	final Properties additionlProperties() {
		return new Properties() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 3996171551371239499L;
			
			{
				// use this to inject additional properties in the EntityManager
				setProperty("hibernate.hbm2ddl.auto", "update");
			}
		};
	}
}
